<?php
/**
 *  ###
 * Example query:
SELECT
    t0.id, t0.name
FROM
    dclub_catalog_tree t0,
    dclub_catalog_tree t1,
    dclub_catalog_tree t2,
    dclub_catalog_tree t3
WHERE
    (t1.name='materialy' AND t1.parentId=0)
    AND
    (t2.name='terapija' AND t2.parentId=t1.id)
    AND
    (t3.name='plombirovo4nye' AND t3.parentId=t2.id)
    AND
    (t0.id IN(t1.id, t2.id, t3.id))

 *
 */
namespace Dclub\modules\Catalog;

class Action_SelectTreePathByNames
    extends Action_SelectTreeAbstract
{

    /**
     *  @var array
     */
    protected $names;


    /************************************
     *         Public methods          *
     ************************************/


    /**
     *  @param array-type $path
     *  @return this
     */
    public function setNames( $path )
    {
        debug();
        $path = \Yz_Array::valueOf($path);
        if (null === $path) {
            throw new \Yz_Exception_InvalidArgument("Path must be an array");
        }
        if (! $path) {
            throw new \Yz_Exception_InvalidArgument("Path must not be empty");
        }
        $this->names = $path;
        return $this;
    }


    /************************************
     *       Protected methods          *
     ************************************/


    /**
     *  Modified SELECT statement creator
     *
     */
    protected function buildSelect()
    {
        debug();
        $path = $this->names;
        if (null === $path) {
            throw new \Yz_Exception("Path not set");
        }
        $sql = parent::buildSelect();

        $joinNr = 0;
        $jids = array();
        $parentId = 0;
        foreach ($path as $name) {
            $joinNr ++;
            $jalias = 'j'. $joinNr;
            $sql->joinTable(
                \Yz_SQL_Join::commaJoin( $this->tableTree, $jalias )
                )
                ->where("({$jalias}.name=:_path{$joinNr} AND {$jalias}.parentId={$parentId})")
                ->bind("_path{$joinNr}", $name)
            ;
            $parentId = $jalias . '.id';
            $jids[] = $parentId;
        }
        $jids = join(',', $jids);
        $sql
            ->where("t0.id IN ($jids)")
            ->orderBy("t0.parentId");
        return $sql;
    }


    /** overridable/extensible join-builder
     *  In this case, index table is completely omitted
     *
     *  @param SQL_SELECT
     *  @return SQL_SELECT
     */
    protected function buildJoin($sql)
    {
        return $sql
        ;
    }


}
